﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DatabaseInterface;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace ObligatorioBD.Logic
{
    class DatabaseCreator
    {
        Connection cnx;
        string catalog;
        Database database;
        Server server;
        Table newTable;
        Index index = null;
        bool createDatabase = false;

        public  DatabaseCreator(Connection cnx, string catalog)
        {
            this.cnx = cnx;
            this.catalog = catalog;
            this.server = new Server(new ServerConnection(cnx.getConnection()));
            this.database = server.Databases[catalog];
            if (database == null)
            {
                this.database = new Database(server, catalog);
                this.createDatabase = true;
            }
        }
        public void NewTable(string tableName)
        {
            this.newTable = new Table(database, tableName);
        }
        public void AddIdentityColumn(string name, DataType type, int seed, int increment)
        {
            Column column = new Column(newTable, name);
            column.DataType = type;
            column.Nullable = false;
            column.Identity = true;
            column.IdentitySeed = seed;
            column.IdentityIncrement = increment;
            newTable.Columns.Add(column);
        }
        public void AddColumn(string name, DataType type, bool nullable, bool isPrimary)
        {
            if (!this.newTable.Columns.Contains(name))
            {
                Column column = new Column(newTable, name);
                column.DataType = type;
                column.Nullable = nullable;
                newTable.Columns.Add(column);
                if (isPrimary)
                {
                    AddColumnKey(name);
                }
            }
        }
        private void AddColumnKey(string columnName)
        {
            if (this.index == null)
            {
                this.index = new Index(this.newTable, "PK_" + this.newTable.Name);
                this.index.IndexKeyType = IndexKeyType.DriPrimaryKey;
            }
            index.IndexedColumns.Add(new IndexedColumn(index, columnName));
        }
        public void CrateTable()
        {
            if (createDatabase)
            {
                this.database.Create();
                this.createDatabase = false;
            }
            this.newTable.Indexes.Add(this.index);
            this.newTable.Create();
            this.index = null;
        }
        public bool CheckNameAvailability()
        {
            return !this.createDatabase;
        }
    }
}
